import { 
    SubscribeMessage,
    WebSocketGateway,
    MessageBody,
    WebSocketServer,
    OnGatewayConnection,
    OnGatewayDisconnect
} from '@nestjs/websockets'
import { Server,Socket } from 'socket.io'
import { UserService } from '../user/user.service'
import { MessageService } from '../message/message.service'
import { IMessage } from '../message/type'

@WebSocketGateway(1080)
export class ChatGateway implements OnGatewayConnection,OnGatewayDisconnect {

    constructor(
        private readonly userService:UserService,
        private readonly messageService:MessageService
    ){}

    @WebSocketServer()
    socket: Server

    async handleConnection(client: Socket, ...args: any[]) {
        await this.userService.updateUser({
            id: +client.handshake.query.user_id,
            isOnline: 2
        })
        this.updateOnlineUser(client)
    }

    async updateOnlineUser(client:Socket){
        try {
            const users = await this.userService.getOnlineUser()
            this.socket.emit('online_users',users)
        } catch (error) {
            client.emit('res_error','查询失败')
        }
    }

    async handleDisconnect(client: any) {
        console.log('disconnect');
        
        await this.userService.updateUser({
            id: +client.handshake.query.user_id,
            isOnline: 1
        })
        this.updateOnlineUser(client)
    }

    @SubscribeMessage('message')
    handleGetMessage(@MessageBody() msg: IMessage & any){        
        const { content,send_time,send_user_id } = JSON.parse(msg)        
        
        this.messageService.handleMessageSave({
            content: content,
            send_time: send_time,
            send_user_id: send_user_id
        })
        this.socket.emit('recieve-msg',msg)
        return msg
    }

}